<template>
  <div>
    <Form
      :oneitem="oneItem"
      :twoitem="twoItem"
      :option="allTaskStatus"
      :search-list="searchList"
      :page-index="pageIndex"
      :config-click-show="configClickShow"
      :total-count="totalCount"
      :total-page="totalPage"
      button-text="工单配置"
      @changeList="changeList"
      @createInflate="createInflate"
      @configCilck="configCilck"
      @newCreateFn="newCreateFn"
      @searchResultFn="searchResultFn"
    >
      <template #tableForm>
        <TableColumn :page-index="pageIndex" @handleClick="handleClick" />
      </template>
    </Form>
    <!-- 新建工单 -->
    <!-- <template #dialogForm> -->
    <el-dialog title="新增工单" :visible.sync="dialogFormVisible" width="630px">
      <el-form ref="dialogForm" :model="dialogForm" :rules="rules">
        <el-form-item label="设备编号" prop="innerCode">
          <el-input v-model="dialogForm.innerCode" type="text" placeholder="请输入内容" maxlength="15" show-word-limit />
        </el-form-item>
        <el-form-item label="工单类型" prop="productType">
          <el-select v-model="dialogForm.productType" placeholder="请选择">
            <el-option value="补货工单" />
          </el-select>
        </el-form-item>
        <el-form-item label="补货数量" prop="details">
          <el-button class="goodsNum" @click="detailsFn"><span>
            <svg-icon icon-class="orderNum" class="icon" />补货清单
          </span></el-button>
          <input v-show="false" v-model="dialogForm.details">
        </el-form-item>
        <el-form-item label="运营人员" prop="assignorId">
          <el-select v-model="dialogForm.assignorId" placeholder="请选择" @focus="optionsFn">
            <el-option v-for="item in options" :key="item.userName" :label="item.userName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input
            v-model="dialogForm.desc"
            type="textarea"
            placeholder="请输入备注（不超过40个字）"
            maxlength="40"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button id="buttom2" @click="createNo">取 消</el-button>
        <el-button id="buttom1" type="primary" @click="createInflate">确 定</el-button>
      </div>
    </el-dialog>
    <!-- </template> -->

    <!-- 售货列表 -->
    <el-dialog title="补货详情" :visible.sync="dialogVisible" width="630px">
      <el-scrollbar style="height: 330px; width:100%;">
        <el-table :data="channelList" style="width: 100%">
          <el-table-column prop="channelCode" label="货道编号" width="92" />
          <el-table-column prop="sku.skuName" label="商品名称" width="92" />
          <el-table-column prop="currentCapacity" label="当前数量" width="92" />
          <el-table-column prop="isaddnum" label="还可添加" width="92" />
          <el-table-column label="补满数量">
            <template slot-scope="scope">
              <span v-if="scope.row.currentCapacity==='-'">货道暂无商品</span>
              <el-input-number
                v-else
                v-model="scope.row.addNum"
                controls-position="right"
                :min="0"
                :max="scope.row.isaddnum"
                @change="handleChange"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer">
        <el-button id="buttom2" @click="noFn">取 消</el-button>
        <el-button id="buttom1" type="primary" @click="yesFn">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 工单详情 -->
    <el-dialog title="工单详情" :visible.sync="taskInfoShow" width="630px">
      <div class="body">
        {{ taskInfoHtml.title }}
      </div>
      <el-form ref="form" :model="taskInfo" label-width="120px">
        <el-row>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="设备编号：">
                {{ taskInfo.innerCode }}
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="创建日期：">
                {{ taskInfo.createTime }}
              </el-form-item>
            </div>
          </el-col>

          <el-col v-if="isDateShow" :span="12">
            <div class="grid-content bg-purple">
              <el-form-item :label=" taskInfoHtml.date">
                {{ taskInfo.updateTime }}
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="运营人员：">
                {{ taskInfo.userName }}
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="工单类型：">
                补货工单
              </el-form-item>
            </div>
          </el-col>
          <!-- 补货详情 -->
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="补货数量：">
                <el-button type="text" @click="productInfo">补货详情</el-button>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="工单方式：">
                {{ taskInfo.createType===0?'自动':'手动' }}
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item :label="taskInfoHtml.desc">
                {{ taskInfo.desc }}
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="isButtonShow" slot="footer" class="dialog-footer">
        <el-button id="buttom2" @click="recreateFn">{{ taskInfoHtml.button }}</el-button>
      </div>
    </el-dialog>
    <!-- 工单配置 -->
    <el-dialog title="工单配置" :visible.sync="configVisible" width="630px">
      <el-form ref="supplyForm" :model="supplyForm" class="demo-ruleForm" :rules="supplyRules">
        <el-form-item label="补货警戒线：" prop="alertValue" label-width="140px">
          <el-input-number v-model="supplyForm.alertValue" controls-position="right" :min="1" :max="100" style="width:396px" @change="handleChange" />
        </el-form-item>
        <el-form-item id="buttom-style">
          <!-- <div slot="footer" class="dialog-footer"> -->
          <el-button id="buttom2" @click="configVisible=false">取 消</el-button>
          <el-button id="buttom1" type="primary" @click="autoSupplyFn">确 定</el-button>
          <!-- </div> -->
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 补货详情列表 -->
    <el-dialog title="补货详情" :visible.sync=" taskDetailsVisible" width="630px">
      <el-scrollbar style="height: 330px; width:100%;">
        <el-table :data="taskDetailsList" style="width: 100%">
          <el-table-column prop="channelCode" label="货道编号" />
          <el-table-column prop="skuName" label="商品名称" />
          <el-table-column prop="expectCapacity" label="补货数量" />
        </el-table>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
// import { taskInfo } from '@/api'
import Form from '@/components/form/index.vue'
import { allTaskStatus, search, create, operatorList, channelList, supplyAlertValue, autoSupplyConfig, cancel, taskDetails } from '@/api'
import TableColumn from './conpenments/tableColumn.vue'
export default {
  components: { Form, TableColumn },
  data() {
    return {
      configClickShow: true,
      // 查看详情
      taskInfo: {},
      taskInfoShow: false,
      taskInfoHtml: {},
      isButtonShow: true,
      isDateShow: true,
      // 添加商品每一项
      product: {
        channelCode: '',
        expectCapacity: '',
        skuId: '',
        skuName: '',
        skuImage: ''
      },
      allTaskStatus: [], // 表单主体
      searchList: [], // 工单状态
      oneItem: '工单编号:',
      twoItem: '工单状态:',
      pageIndex: 1,
      totalCount: null, // 所有数量
      totalPage: null, // 所有页数
      labelPosition: 'right',
      dialogVisible: false, // 售货列表
      addList: [],
      // 新建工单
      dialogFormVisible: false,
      dialogForm: {
        innerCode: '',
        productType: '',
        details: [],
        assignorId: '',
        desc: ''
      },
      rules: {
        innerCode: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        productType: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        assignorId: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        details: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      channelList: [], // 售货列表
      options: [], // 人员名单
      value: '',
      configVisible: false,
      supplyForm: {
        alertValue: 0
      }, // 预警值
      supplyRules: {
        alertValue: [
          { required: true, trigger: 'blur' }
        ]
      },
      // 补货详情列表
      taskDetailsList: [],
      taskDetailsVisible: false
    }
  },
  async created() {
    const res = await allTaskStatus()
    this.allTaskStatus = res.data
    await this.searchFn(this.pageIndex)
  },
  methods: {
    // 搜索功能
    searchResultFn(form) {
      // console.log(id)
      this.searchFn(1, form)
    },
    // 新建
    newCreateFn() {
      this.dialogFormVisible = true
    },
    // 查看详情
    async handleClick(row) {
      this.taskInfoHtml = {}
      // console.log(row)
      if (row.taskStatus === 1) {
        this.taskInfoHtml = {
          title: '代办',
          button: '取消工单',
          desc: '备注：'
        }
        this.isDateShow = false
      } else if (row.taskStatus === 3) {
        this.taskInfoHtml = {
          title: '取消',
          button: '重新创建',
          desc: '取消原因：',
          date: '取消时间：'
        }
        this.isDateShow = true
      } else if (row.taskStatus === 4) {
        this.taskInfoHtml = {
          title: '完成',
          desc: '备注',
          date: '完成时间：'
        }
        this.isButtonShow = false
      }
      this.taskInfo = row
      this.taskInfoShow = true
    },
    // 列表接口
    async searchFn(pageIndex, status) {
      const res = await search({
        pageIndex,
        pageSize: 10,
        isRepair: false,
        ...status
      })
      this.totalCount = res.data.totalCount
      this.totalPage = res.data.totalPage
      this.searchList = res.data.currentPageRecords
      for (let i = 0; i < this.searchList.length; i++) {
        this.searchList[i].createTime = this.searchList[i].createTime.replace(/-/g, '.').replace(/T/, ' ')
        if (this.searchList[i].createType === 1) {
          this.searchList[i].createType = '手动'
        } else {
          this.searchList[i].createType = '自动'
        }
      }
    },
    async changeList(pageIndex) {
      this.pageIndex = pageIndex
      this.searchFn(pageIndex)
    },
    // indexMethod(index) {
    //   return this.pageIndex === 1 ? index + 1 : Number(`${this.pageIndex - 1}${index}`) + 1
    // },
    // 添加 工单接口
    async createInflate() {
      const obj = {
        createType: 1,
        userId: this.$store.state.user.userId,
        innerCode: this.dialogForm.innerCode,
        productType: 2,
        desc: this.dialogForm.desc,
        details: this.addList,
        assignorId: 40 // 工单分配人Id
      }
      const res = await create(obj)
      if (res.data === true) {
        this.dialogFormVisible = false
        this.$refs.dialogForm.resetFields()
        await this.searchFn(1)
      }
    },
    createNo() {
      this.dialogFormVisible = false
      this.$refs.dialogForm.resetFields()
    },
    // 获取运营人员列表
    async optionsFn() {
      if (this.dialogForm.innerCode) {
        const res = await operatorList(this.dialogForm.innerCode)
        this.options = res.data
        // console.log(this.options)
      } else {
        this.$refs.dialogForm.validateField('innerCode')
      }
    },
    // 获取售货详情
    async detailsFn() {
      if (this.dialogForm.innerCode) {
        this.dialogVisible = true
        // console.log(this.dialogForm.innerCode)
        const res = await channelList(this.dialogForm.innerCode)
        // console.log(res)
        res.data.forEach(item => {
          if (!item.sku) {
            item.sku = { skuName: '-' }
            item.isaddnum = '-'
            item.currentCapacity = '-'
          }
          if (item.currentCapacity >= 10) {
            item.isaddnum = 0
            item.addNum = 0
          } else if (item.currentCapacity >= 0) {
            item.isaddnum = 10 - item.currentCapacity
            item.addNum = item.isaddnum
          }
        })
        this.channelList = res.data
        // console.log(this.channelList)
      } else {
        this.$refs.dialogForm.validateField('innerCode')
      }
    },
    handleChange(val) {
      console.log(val)
    },
    noFn() {
      console.log(1)
      this.dialogVisible = false
    },
    // 确定添加 货物按钮
    yesFn() {
      this.channelList.filter(item => item.addNum > 0).forEach(item => {
        this.product.channelCode = item.channelCode
        this.product.expectCapacity = item.addNum
        this.product.skuId = item.skuId
        this.product.skuName = item.sku.skuName
        this.product.skuImage = item.sku.skuImage
        this.addList.push(this.product)
      })
      this.dialogVisible = false
    },
    // 重新创建
    async recreateFn() {
      // console.log(this.taskInfo)
      if (this.taskInfo.taskStatus === 3) {
        this.taskInfoShow = false
        this.dialogFormVisible = true
        // console.log(this.taskInfo.taskId)
        const res = await taskDetails(this.taskInfo.taskId)
        this.dialogForm = {
          innerCode: this.taskInfo.innerCode,
          productType: '补货工单',
          details: res.data,
          assignorId: this.taskInfo.userName,
          desc: this.taskInfo.desc
        }
        this.addList = res.data
      } else {
        this.$confirm('', '取消工单后，将不能恢复，是否确认取消？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(async() => {
          await cancel({ taskId: this.taskInfo.taskId })
          this.taskInfoShow = false
          this.$message({
            type: 'success',
            message: '已取消工单!'
          })
          await this.searchFn(this.pageIndex)
        }).catch(() => { })
      }
    },
    // 补货详情
    async productInfo() {
      // console.log(this.taskInfo)
      const res = await taskDetails(this.taskInfo.taskId)
      // console.log(res.data)
      this.taskDetailsList = res.data
      this.taskDetailsVisible = true
    },
    // 工单配置
    async configCilck() {
      const res = await supplyAlertValue()
      this.supplyForm.alertValue = res.data
      console.log(res.data)
      this.configVisible = true
    },
    async autoSupplyFn() {
      console.log(this.supplyForm.alertValue)
      this.configVisible = false
      await autoSupplyConfig({ alertValue: this.supplyForm.alertValue })
    }
  }
}
</script>

<style lang="scss" >
.goodsNum {
  border: none;
  color: #5f84ff;
  background-color: #fff;

  &:hover {
    background-color: #fff;
  }

  .icon {
    color: #5f84ff !important;
    margin-right: 5px;
  }
}

#buttom1 {
  align-items: center;
  width: 80px !important;
  height: 36px;
  padding: 0;
  background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
  color: #fff;
  border: none;
}

#buttom2 {
  align-items: center;
  width: 80px !important;
  height: 36px;
  padding: 0;
  background-color: #fbf4f0 !important;
  border: none;
  color: #655b56 !important;
}

.sidebar-wrapper .el-scrollbar__wrap {
  overflow-x: hidden;
}

.is-horizontal {
  display: none;
}

.el-col {
  height: 36px;
}

.body {
  height: 54px;
  margin-bottom: 25px;
  background-color: hsla(0, 0%, 92.5%, .39);
}
// .el-input-number{
//   width: 396px;
// }
#buttom-style{
  .el-form-item__content{
    margin: 0 !important;
    text-align: center;
  }
}
</style>
